package com.learn.english.service.impl;


import com.learn.english.enums.ResultCode;
import com.learn.english.exception.BusinessException;
import com.learn.english.mapper.UserMapper;
import com.learn.english.model.dto.RegisterDto;
import com.learn.english.model.entity.User;
import com.learn.english.service.IRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.UUID;

/**
 * @author TISNIW
 * @version 1.0
 * @date 2025/4/25 22:47
 * @desc
 */
@Service
public class RegisterServiceImpl implements IRegisterService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Override
    public String register(RegisterDto registerDto) {
        // 1. 检查用户名或邮箱是否已存在
        if (userMapper.queryByUsername(registerDto.getUsername()) != null) {
            throw new BusinessException(ResultCode.USER_NAME_EXIST);
        }

        if (userMapper.queryByEmail(registerDto.getEmail()) != null) {
            throw new BusinessException(ResultCode.EMAIL_REGISTERED);
        }

        // 2. 加密密码
        String encodedPassword = encoder.encode(registerDto.getPassword());

        // 3. 生成唯一ID
        Long userId = generateUserId();
        String uid = new  BigDecimal(1000000).add(BigDecimal.valueOf(userId)).toString();

        // 4.检查用户头像
        if (registerDto.getAvatarUrl() == null || registerDto.getAvatarUrl().isEmpty() || "".equals(registerDto.getAvatarUrl())) {
            registerDto.setAvatarUrl("/avatar/get?url=default.png");
        }

        // 5. 构造 User 对象并插入数据库
        User user = User.builder()
                .id(userId)
                .username(registerDto.getUsername())
                .email(registerDto.getEmail())
                .password(encodedPassword)
                .avatarUrl(registerDto.getAvatarUrl())
                .uid(uid)
                .build();

        int result = userMapper.addUser(user);
        if (result <= 0) {
            throw new BusinessException(ResultCode.REGISTER_FAILED);
        }

        return "注册成功";
    }
    private Long generateUserId() {
        Integer maxId = userMapper.queryMaxId();
        return maxId == null ? 1L : maxId + 1L;
    }
}
